﻿using Microsoft.Extensions.Hosting;
using Nacos.V2;
using Nacos.V2.Common;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NetMicro.Core.Extensions;
using NetMicro.Core.Helper;
using NetMicro.Nacos.Abstractions;
using NetMicro.Nacos.Exceptions;

namespace NetMicro.Nacos
{
    /// <summary>
    /// 服务发现获取服务调用地址
    /// </summary>
    public class ServiceClient : IServiceClient
    {
        private readonly INacosNamingService _nacosNamingService;
        private readonly IHostEnvironment _hostEnvironment;
        public ServiceClient(INacosNamingService nacosNamingService, IHostEnvironment hostEnvironment)
        {
            _nacosNamingService = nacosNamingService;
            _hostEnvironment = hostEnvironment;
        }

        /// <summary>
        /// 获取服务地址
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public async Task<string> GetAsync(string serviceName)
        {
            if (_hostEnvironment.IsDevelopment())
            {
                var options = App.GetConfig<List<LocalServiceOptions>>("LocalService");
                var baseUrl = options?.FirstOrDefault(m => m.Key == serviceName)?.Value;
                if (!baseUrl.IsNull())
                    return baseUrl;
            }
            var instance = await _nacosNamingService.SelectOneHealthyInstance(serviceName, Constants.DEFAULT_GROUP);
            if (instance?.Healthy == true)
                return $"http://{ instance.Ip}:{instance.Port}";
            throw new NacosException($"未发现{serviceName}实例");
        }
    }
}
